package com.unidt.www.module.third.doc.service.impl;

import com.alibaba.fastjson.JSON;
import com.unidt.www.framework.common.exception.ServiceException;
import com.unidt.www.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.unidt.www.framework.common.util.object.BeanMapUtils;
import com.unidt.www.module.third.doc.dao.DocInfoMapper;
import com.unidt.www.module.third.doc.dao.ProjectBusInfoMapper;
import com.unidt.www.module.third.doc.dao.ProjectPlanMapper;
import com.unidt.www.module.third.doc.domain.DocInfoDo;
import com.unidt.www.module.third.doc.domain.ProjectBusInfoDo;
import com.unidt.www.module.third.doc.domain.ProjectPlanDo;
import com.unidt.www.module.third.doc.service.IDocService;
import com.unidt.www.module.third.doc.utils.HtmlDocUtils;
import com.unidt.www.module.third.doc.utils.HtmlUtils;
import com.unidt.www.module.third.doc.utils.TableDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author sk
 * @Description:
 * @Date 2022/11/24 18:18
 **/
@Service
@Slf4j
public class DocServiceImpl implements IDocService {

    @Autowired
    DocInfoMapper docInfoMapper;

    @Autowired
    ProjectBusInfoMapper projectBusInfoMapper;

    @Autowired
    ProjectPlanMapper projectPlanMapper;

    /**
     * 文件上传路径
     */
    @Value("${file.doc.tmpPath}")
    String docTmpPath ;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean parse(Long docId) {

        DocInfoDo docInfoDo = this.docInfoMapper.selectById(docId);
        if(Objects.isNull(docInfoDo)){
            throw  new  ServiceException(GlobalErrorCodeConstants.UNKNOWN.getCode(),"文件编号不存在");
        }        /**
         * 查看是否解析完成
         */
        ProjectBusInfoDo busInfoDo = this.projectBusInfoMapper.getByDocId(docId);
        if(Objects.isNull(busInfoDo)){
            String htmlPath = docInfoDo.getHtmlPath();
            List<TableDto> tables = new ArrayList<>();

            tables.add(new TableDto("项目分年度建设进度计划", "项目分年度建设进度计划", "项目的技术先进性比较优势分析"));

            Map<String, Object> result = HtmlDocUtils.parseHtml(htmlPath, 0,2, tables);

            log.info("原始信息:{}",JSON.toJSONString(result));
            Map<String, Object> dataMap = BeanMapUtils.transForObject(result, ProjectBusInfoDo.class);

            String jsonStr = JSON.toJSONString(dataMap);

            ProjectBusInfoDo projectBusInfoDo = JSON.parseObject(jsonStr,ProjectBusInfoDo.class);
            projectBusInfoDo.setDocId(docId);


            List<ProjectPlanDo> projectPlanDos =  projectBusInfoDo.getPlanList();

            if(projectPlanDos==null || projectPlanDos.isEmpty()){
                docInfoDo.setSuccess(false);
                docInfoDo.setErrorMessage("文档内容读取不不全");
                this.docInfoMapper.updateById(docInfoDo);

            }else {

                this.projectBusInfoMapper.insert(projectBusInfoDo);

                Long projectBusId =  projectBusInfoDo.getId();
                projectPlanDos.forEach(p->{
                    p.setProjectBusId(projectBusId);
                    if(p.validate()){
                        this.projectPlanMapper.insert(p);
                    }

                });
                docInfoDo.setSuccess(true);
                this.docInfoMapper.updateById(docInfoDo);
                return  true;
            }

        }

        return false;

    }

    @Override
    public DocInfoDo upload(MultipartFile file) {
        try {
            /**
             * 文件零时目录
             */
            DocInfoDo docInfoDo =  new DocInfoDo();
            String fileName = file.getOriginalFilename();
            String name = String.valueOf(System.currentTimeMillis());
            String folder = docTmpPath+"/"+name;
            File f = new File(folder);
            if(!f.exists()){
                f.mkdir();
            }

            String fullPath = folder+"/"+fileName;
            docInfoDo.setFolder(folder);
            docInfoDo.setName(fileName);

            docInfoDo.setPath(fullPath);

            String htmlPath = folder+"/"+name+".html";
            file.transferTo(new File(fullPath));

            HtmlUtils.saveToHtml(fullPath,htmlPath);
            docInfoDo.setHtmlPath(htmlPath);

            this.docInfoMapper.insert(docInfoDo);

            return  docInfoDo;
        }catch (Exception e){

            log.error("文件上传失败",e);
           throw  new  ServiceException(GlobalErrorCodeConstants.UNKNOWN.getCode(),"文件上传失败");
        }

    }

    @Override
    public ProjectBusInfoDo getParse(Long docId) {
        ProjectBusInfoDo busInfoDo = this.projectBusInfoMapper.getByDocId(docId);
        if(Objects.nonNull(busInfoDo)){
            List<ProjectPlanDo> planDos = this.projectPlanMapper.getPlansByBusId(busInfoDo.getId());
            busInfoDo.setPlanList(planDos);
        }

        return busInfoDo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDoc(DocInfoDo docInfoDo) {
        this.docInfoMapper.insert(docInfoDo);
    }


}
